﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using DevExpress.LocalizationCHS;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid.Columns;

using DevExpress.XtraEditors.Repository;

using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using JsalesModel;


namespace JSales.ModuleProduct
{
    public partial class PriceSetForm : Form
    {
        public PriceSetForm()
        {
            InitializeComponent();
            InitValidationRules();
        }

        private EditMode mode;

        private enum EditMode
        {
            Normal = 0,
            Edit = 1,
            Add = 2
        }

        private void ChangeEditMode(EditMode editMode)
        {
            switch (editMode)
            {
                case EditMode.Normal:
                    {
                        mode = EditMode.Normal;
                        gridViewPrice.OptionsBehavior.Editable = false;
                        gridViewPrice.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;

                        barButtonSave.Enabled = false;
                        barButtonCancel.Enabled = false;
                        barButtonEdit.Enabled = true;
                        barButtonDelete.Enabled = true;
                        barButtonAdd.Enabled = true;

                        LookupEditLevel.Enabled = false;
                        calcEditPrice.Enabled = false;

                        dxValidationProvider1.RemoveControlError(LookupEditLevel);
                        dxValidationProvider1.RemoveControlError(calcEditPrice);
                    }
                    break;
                case EditMode.Edit:
                    {
                        mode = EditMode.Edit;
                        gridViewPrice.OptionsBehavior.Editable = false;
                        gridViewPrice.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;

                        barButtonSave.Enabled = true;
                        barButtonCancel.Enabled = true;
                        barButtonEdit.Enabled = false;
                        barButtonDelete.Enabled = false;
                        barButtonAdd.Enabled = false;

                        LookupEditLevel.Enabled = false;
                        calcEditPrice.Enabled = true;

                        dxValidationProvider1.Validate();
                    }
                    break;
                case EditMode.Add:
                    {
                        mode = EditMode.Add;
                        gridViewPrice.OptionsBehavior.Editable = false;
                        gridViewPrice.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;

                        barButtonSave.Enabled = true;
                        barButtonCancel.Enabled = true;
                        barButtonEdit.Enabled = false;
                        barButtonDelete.Enabled = false;
                        barButtonAdd.Enabled = false;

                        LookupEditLevel.Enabled = true;
                        calcEditPrice.Enabled = true;
                        LookupEditLevel.EditValue = 0;

                        dxValidationProvider1.Validate();
                    }
                    break;
            }
        }

        private BindingSource bindingSource = new BindingSource();
        BindingSource priceBind = new BindingSource();

        private void InitValidationRules()
        {
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = "值不能为空！";

            dxValidationProvider1.ValidationMode = ValidationMode.Auto;
            dxValidationProvider1.SetValidationRule(LookupEditLevel, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(calcEditPrice, notEmptyValidationRule);
        }

        private string selectProduct ;
        private IQueryable<TbPrice> iPrices;

        private void GetPricesList()
        {
            var dbContext = new JYEntities();
            iPrices = from i in dbContext.TbPrices
                     where i.ProductID == selectProduct
                     select i;
            if (iPrices.Any())
            {
                priceBind.DataSource = iPrices;
            }
        }


        private bool PriceisExist(string productid,Int32 level)
        {
            var dbContext = new JYEntities();
            IQueryable<TbPrice> prices = from i in dbContext.TbPrices
                                             where i.ProductID == productid&&i.Level==level
                                             select i;
            if (prices.Any())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void PriceSetForm_Load(object sender, EventArgs e)
        {
            ChangeEditMode(EditMode.Normal);
            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;

            IQueryable<TbProduct> products = from i in GlobalVar.GProductsRaw.Union(GlobalVar.GProductsSemi.Union(GlobalVar.GProducts))
                                             where i.IsDeleted == false
                                             select i
                                             ;
            if (products.Any())
            {
                bindingSource.DataSource = products;
                gridControl1.DataSource = products;

                repositoryItemLookUpEditKind.DataSource = GlobalVar.GKinds;
                repositoryItemLookUpEditColor.DataSource = GlobalVar.GColors;
                repositoryItemLookUpEditTexture.DataSource = GlobalVar.GTextures;
                repositoryItemGridLookUpEditTypes.DataSource = GlobalVar.typeses;
            }

            LookupEditLevel.Properties.NullText = "请指定客户级别...";
            LookupEditLevel.Properties.DataSource = GlobalVar.GCusLevels;
            LookupEditLevel.Properties.TextEditStyle=TextEditStyles.DisableTextEditor;
        }
        
        private void BarButtonAddItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeEditMode(EditMode.Add);
        }

        private void barButtonSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (mode == EditMode.Normal)
            {
                return;
            }
            else
            {
                var dbConText = new JYEntities();

                int level = int.Parse(LookupEditLevel.EditValue.ToString());

                if (mode == EditMode.Add)
                {
                    if (PriceisExist(selectProduct, level))
                    {
                        MessageBox.Show("该产品该级别订价已存在！");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(LookupEditLevel.Text)
                            && !string.IsNullOrEmpty(calcEditPrice.Value.ToString()))
                        {
                            TbPrice price =new TbPrice();
                            price.ProductID = selectProduct;
                            price.Level = level;
                            price.Price = (double)calcEditPrice.Value;

                            dbConText.Add(price);
                            dbConText.SaveChanges();

                            IQueryable<TbPrice> prices = from i in dbConText.TbPrices
                                                         where i.ProductID == selectProduct
                                                         select i;
                            gridViewPrice.ClearSelection();
                            if (prices.Any())
                            {
                                gridControlPrice.DataSource = prices.ToList();
                                gridViewPrice.RefreshData();
                            }
                        }
                        else
                        {
                            MessageBox.Show("数据请填写完整！");
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(LookupEditLevel.Text)
                        && !string.IsNullOrEmpty(calcEditPrice.Value.ToString()))
                    {
                        IQueryable<TbPrice> prices = from i in dbConText.TbPrices
                                                     where i.ProductID == selectProduct && i.Level == level
                                                     select i;

                        if (prices.Any())
                        {
                            TbPrice price = prices.FirstOrDefault();
                            price.Price = Convert.ToDouble(calcEditPrice.EditValue);

                            dbConText.SaveChanges();

                            prices = from i in dbConText.TbPrices
                                                         where i.ProductID == selectProduct
                                                         select i;
                            gridViewPrice.ClearSelection();
                            if (prices.Any())
                            {
                                gridControlPrice.DataSource = prices.ToList();
                                gridViewPrice.RefreshData();
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("数据请填写完整！");
                    }
                }
            }
            ChangeEditMode(EditMode.Normal);
        }

        private void barButtonEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeEditMode(EditMode.Edit);
        }

        private void barButtonCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridControl1.FocusedView.CloseEditor();
            ChangeEditMode(EditMode.Normal);
        }

        private void barButtonFind_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.FindPanelVisible = true;
        }

        private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            int selectedHandle;
            selectedHandle = gridView1.GetSelectedRows()[0];
            selectProduct = gridView1.GetRowCellValue(selectedHandle, "ProductID").ToString();

            if (GlobalVar.GPrices != null)
            {
                GetPricesList();
//                var dbContext = new JYEntities();
//                IQueryable<TbPrice> prices = from i in dbContext.TbPrices
//                                             where i.ProductID == selectProduct
//                                             select i;
                gridViewPrice.ClearSelection();
                if (iPrices.Any())
                {
                    repositoryItemLookUpEditLevel.DataSource = GlobalVar.GCusLevels;

                    gridControlPrice.DataSource = priceBind;
                    gridViewPrice.RefreshData();
                }
                else
                {
                    gridControlPrice.DataSource = null;
                }
            }
            else
            {
                gridControlPrice.DataSource = null;
            }

        }

        private void gridViewPrice_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {

            //int selectedHandle;
            //selectedHandle = gridViewPrice.GetSelectedRows()[0];
            //string SelectLevel = gridViewPrice.GetRowCellValue(selectedHandle, "Level").ToString();
            //string SelectPrice = gridViewPrice.GetRowCellValue(selectedHandle, "Price").ToString();

            if (selectProduct != null && iPrices.Any())
            {
                
               // LookupEditLevel.EditValue = Int32.Parse(SelectLevel);
               // calcEditPrice.EditValue = int.Parse(SelectPrice);

                  GetPricesList();
                  
                  
                  //priceBind.DataSource = iPrices;
                  
                  LookupEditLevel.DataBindings.Clear();
                  calcEditPrice.DataBindings.Clear();
                  
                  LookupEditLevel.DataBindings.Add("EditValue", priceBind, "Level");
                  calcEditPrice.DataBindings.Add("EditValue", priceBind, "Price");
                  
                  gridControlPrice.DataSource = priceBind;  

//                var dbContext = new JYEntities();
//                IQueryable<TbPrice> prices = from i in dbContext.TbPrices
//                                             where i.ProductID == selectProduct
//                                             select i;
//                gridViewPrice.ClearSelection();
//                if (prices.Any())
//                {
//                    repositoryItemLookUpEditLevel.DataSource = GlobalVar.GCusLevels;
//
//                    gridControlPrice.DataSource = prices.ToList();
//                    gridViewPrice.RefreshData();
//                }
//                else
//                {
//                    gridControlPrice.DataSource = null;
//                }
            }
            else
            {
                gridControlPrice.DataSource = null;
            }
        }
        

    }
}
